/**
 * @description: 处理文件相关api
 * @author: tao wenbo 2419421809@qq.com
 */
import express from "express";
import fs from "fs";
import path from "path";
import { MyFileDir } from "../../model/models/MyFileDirTable";
import { getIpAddress } from "@/utils/getIp";
import { PORT, VideoExt, ImgExt, staticPath, staticPathName } from "@/utils/const";
import { CODE } from "../../utils/const";
import { ReturnData, MyFileDirItf } from "../../interface/interface";
import { Op } from "sequelize";

const router = express.Router();

// 文件内容的返回值
interface FileItf {
    path: string;
    isFile: boolean;
    isDir: boolean;
    ext: string;
    filename: string;
    thumbnailAddress: string;
}


interface GetDirFileItf{
    folder: MyFileDirItf[];
    imgs: MyFileDirItf[];
    videos: MyFileDirItf[];
    currentFolderName: string;
    currentPath: string;
}


/**
 * @description: 直接从数据库中查询
 * @param {*} getDirFile
 * @param { string } req.query.routerId 没有router用id
 * @param { string } req.query.router 有router先用router
 * @return {*}
 * @author: tao wenbo 2419421809@qq.com
 */
router.get("/getDirFile", async (req, res) => {
    
    let returnData: ReturnData<GetDirFileItf> = {
        code: CODE.errorCode,
        data: {
            imgs:[],
            videos: [],
            folder: [],
            currentFolderName: "",
            currentPath: ""
        }
    };
    let parentId: number = -1;
    let currentFolder = "";
    if (!req.query.routerId) {
        let result = await MyFileDir.findOne({
            where: {
                path: req.query.router,
            },
        });
        parentId = result?.dataValues.id || -1;
        currentFolder = result?.dataValues.path;
    } else {
        // 如果传id
        let result = await MyFileDir.findOne({
            where: {
                id: req.query.routerId,
            },
        });
        parentId = result?.dataValues.id || -1;
        currentFolder = result?.dataValues.path;
    }

    if (parentId !== -1) {
        let files = await MyFileDir.findAll({
            where: {
                parentId,
            },
        });
        let ip = getIpAddress();

        let folder: MyFileDirItf[] = [];
        let imgs: MyFileDirItf[] = [];
        let videos: MyFileDirItf[] = [];
        let hostPost = `http://${ip}:${PORT}/static`;
        for (const file of files) {
            let data: MyFileDirItf = file.dataValues;
            data.relativePath = data.path
            data.path = `${hostPost}${data.path.trim()}`;
            data.thumbnailPath = data.thumbnailPath.trim() ? `${hostPost}${data.thumbnailPath.trim()}` : "";
            data.fileName = path.basename(data.path, data.ext);


            if (VideoExt.includes(data.ext.toLowerCase())) {
                videos.push(data);
            } else if (ImgExt.includes(data.ext.toLowerCase())) {
                imgs.push(data);
            } else if (!data.isFile) {
                folder.push(data);
            }
        }

        returnData.data!.imgs = imgs
        returnData.data!.videos = videos;
        returnData.data!.folder = folder;
        returnData.code = CODE.successCode;
        returnData.data!.currentFolderName = `${currentFolder || 'static'}`;
        returnData.data!.currentPath = `${hostPost}${currentFolder}`
    } else {
        returnData.code = CODE.errorCode;
        returnData.meg = "该目录不存在";
    }
    res.send(returnData);
});

/**
 * @description: 通过名字模糊查询
 * @param {string} serName
 * @author: tao wenbo 2419421809@qq.com
 */
router.get("/searchDir", async (req, res) => {
    let serName = req.query.serName;
    let result = await MyFileDir.findAll({
        where: {
            path: {
                [Op.like]: `%${serName}%`,
            },
            isFile: false,
        },
    });
    let arr: MyFileDirItf[] = result.map((item) => item.dataValues);
    let data: MyFileDirItf[] = [];
    for (const item of arr) {
        let id = item.parentId;
        let length = arr.filter((a) => a.id === id).length;
        item.fileName = path.basename(item.path, item.ext);
        if (length == 0) {
            data.push(item);
        }
    }
    let returnData: ReturnData<GetDirFileItf> = {
        code: CODE.successCode,
        data:{
            imgs: [],
            folder: data,
            videos: [],
            currentFolderName: serName as string,
            currentPath: ""
        },
        count: data.length,
    };
    res.send(returnData);
});

export default router;
